package com.zyk.leetcode;

/**
 * @author zhangsan
 * @date 2021/6/13 15:39
 */
public class C37 {

    boolean[][] rows = new boolean[9][9];
    boolean[][] cols = new boolean[9][9];
    boolean[][] boxes = new boolean[9][9];

    public void solveSudoku(char[][] board) {
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                // 每3行算一行 * 3 + 列下标
                if (board[i][j] != '.') {
                    int box_index = (i / 3) * 3 + j / 3;
                    int v = board[i][j] - '1';
                    rows[i][v] = cols[j][v] = boxes[box_index][v] = true;
                }
            }
        }
        process(board, 0, 0);
    }

    public boolean process(char[][] board, int i, int j) {
        if (i == 9) return true;
        int nextI = j == 8 ? i + 1 : i;
        int nextJ = j == 8 ? 0 : j + 1;
        if (board[i][j] != '.') {
            return process(board, nextI, nextJ);
        } else {

            int box_index = (i / 3) * 3 + j / 3;
            for (char v = 0; v < 9; v++) {
                if (rows[i][v] || cols[j][v] || boxes[box_index][v]) {
                    continue;
                }
                rows[i][v] = cols[j][v] = boxes[box_index][v] = true;
                board[i][j] = (char) (v + '1');

                if (process(board, nextI, nextJ)) {
                    return true;
                }

                rows[i][v] = cols[j][v] = boxes[box_index][v] = false;
                board[i][j] = '.';
            }

            return false;
        }
    }


    // for test
    public static void main(String[] args) {
        char[][] board = {{'5', '3', '.', '.', '7', '.', '.', '.', '.'}, {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, {'.', '.', '.', '.', '8', '.', '.', '7', '9'}};
        new C37().solveSudoku(board);
    }

}
